const XLSX = require('../../utils/xlsx.mini.min');
import { getAllStudent ,getAllCourse, gradeImport,getCourseById,updateScore} from "../../api/score";

Page({
  data: {
    scoreList: [
      
    ],
    editDialogVisible: false,
    currentScore: {},
    excelData: [],
    fileName: '',
    theFileList: [],
    courses: [],
    selectedCourse: '', // 选中的课程
    allStudent:[],
    CourseList:[],
    selectedCourseId:'',
    courseNames:''
  },
  // 处理课程选择
  async onCourseChange(e) {
    const selectedIndex = e.detail.value; // 选中的索引
    const selectedCourse = this.data.courses[selectedIndex]; // 获取选中的课程对象
    this.setData({
      selectedCourse: selectedCourse.name, // 设置显示的课程名称
      selectedCourseId: selectedCourse.id // 保存选中的课程 ID
    });
    const res = await getCourseById(this.data.selectedCourseId)
    // 去重逻辑
    const uniqueScoreList = res.data.filter((item, index, self) =>
    index === self.findIndex((t) => t.studentNo === item.studentNo)
    );

    this.setData({
    scoreList: uniqueScoreList
    });
  },
  // 上传 Excel 文件
  uploadExcel() {
    console.log("点击上传了");
    wx.chooseMessageFile({
      count: 1,
      type: 'file',
      success: (res) => {
        // 获取文件路径
        const filePath = res.tempFiles[0].path;
        console.log('----',filePath);

        // 读取文件内容
        wx.getFileSystemManager().readFile({
          filePath: filePath,
          encoding: 'base64',
          success: (fileRes) => {
            // 使用 xlsx 读取工作簿
            const workbook = XLSX.read(fileRes.data, { type: 'base64' });
            const sheetNameList = workbook.SheetNames;

            // 获取第一个工作表的数据
            const data = XLSX.utils.sheet_to_json(workbook.Sheets[sheetNameList[0]]);
            const fileName = res.tempFiles[0].name;

            // 更新文件列表和解析后的数据
            console.log('学生',this.data.allStudent);
            const updatedExcelData = data.map(item => {
              // 查找匹配的学生记录
              const student = this.data.allStudent.find(apiItem => apiItem.studentNo == item['学号']);
              console.log('student',student);
              return {
                studentId: student ? student.studentId : null, // 如果找不到匹配，返回 null
                studentNo: item['学号'] ? String(item['学号']) : null,
                studentName: item['姓名'] ? item['姓名'] : null,
                score: item['成绩'] ? Number(item['成绩']) : null,
                examType: item['类型'] ? item['类型'] : null
              };
            });
            console.log('updatedExcelData',updatedExcelData);
            this.setData({
              fileName: fileName,
              theFileList: [...this.data.theFileList, fileName],
              excelData: updatedExcelData
            });
  
            console.log(this.data.fileName);
            console.log("bbbb",this.data.theFileList);
            this.triggerEvent('dataChange', this.data.excelData);

           

            // 将解析后的数据添加到成绩列表中
            this.updateScoreList(this.data.excelData);
          },
          fail: (error) => {
            console.error('读取文件失败', error);
          },
        });
      },
      fail: (error) => {
        console.error('选择文件失败', error);
      },
    });
  },

  // 更新成绩列表
  updateScoreList(newData) {
    const updatedList = [...this.data.scoreList];

    newData.forEach(item => {
      const index = updatedList.findIndex(score => score.studentId === item.studentId);
      if (index !== -1) {
        // 更新已有成绩
        updatedList[index].score = item.score;
        updatedList[index].type = item.type; // 如果需要更新类型，可以添加
      } else {
        // 添加新成绩
        updatedList.push(item);
      }
    });

    const uniqueScoreList = updatedList.filter((item, index, self) =>
    index === self.findIndex((t) => t.studentNo === item.studentNo)
  );
  
  this.setData({
    scoreList: uniqueScoreList
  });
  

    wx.showToast({
      title: '上传成功',
      icon: 'success',
    });
  },

  // 点击操作按钮
  onEditClick(e) {
    const index = e.currentTarget.dataset.index;
    const score = this.data.scoreList[index];

    this.setData({
      editDialogVisible: true,
      currentScore: { ...score }, // 深拷贝当前成绩
    });
  },

  // 输入新成绩
  onScoreInput(e) {
    this.setData({
      'currentScore.score': e.detail.value,
    });
  },

  onCancelEdit: function () {
    this.setData({
        editDialogVisible: false,
        currentScore: null // 或者其他处理
    });
},


  // 确认编辑
  async onConfirmEdit() {
    const updatedScore = this.data.currentScore;
    const index = this.data.scoreList.findIndex(item => item.studentId === updatedScore.studentId);
    console.log('updatedScore',updatedScore,index);
    if(updatedScore.score>100||updatedScore.score<0){
      wx.showToast({
        title: '编辑失败，请重新编辑',
        icon: 'none',
      });
    }
    else{
      const res= await updateScore(updatedScore)

      if (res.code===200) {
        // 更新成绩列表
        const updatedList = [...this.data.scoreList];
        updatedList[index].score = updatedScore.score;
        this.setData({
          scoreList: updatedList,
          editDialogVisible: false,
        });
        wx.showToast({
          title: '编辑成功',
          icon: 'success',
        });
      }
    }
    
  
  },
  async onOk(){
    console.log('----sss',this.data.selectedCourse);
    const result = this.data.scoreList.map(item => ({
      studentId: item.studentId,
      score: item.score,
      examType: item.examType,
      courseId: this.data.selectedCourseId
  }));
  console.log('result',result);
  let hasError = false;
 // 定义预期列数
 const expectedColumns = 5; 
  this.data.excelData.some(item => {
    console.log('--it',Object.values(item));
    Object.values(item).some(value => {
      const columnCount = Object.keys(item).length;
        if (columnCount !== expectedColumns) {
          console.log('----c',columnCount);
            
            hasError = true;
        }
        if (value === null || value === undefined) {
            console.log("发现空值:", value); // 输出当前值
            hasError = true;
          }
          if (item.score < 0 || item.score > 100) {
            console.log('---sasasasas',item.score);
           
            hasError = true;
        }    
      });
});

if (hasError) {
    wx.showToast({
      title: '录入失败，请重新录入',
      icon: 'none',
    });

}else{
  const res = await gradeImport(result)
  this.setData({
    theFileList:''
  })
  wx.showToast({
    title: '录入成功',
    icon: 'success',
  });
}



  
  },
 async onLoad(){
   const res=await getAllStudent()
   const getCourseList=await getAllCourse()
   this.setData({
     allStudent:res.data,
     CourseList:getCourseList.data,
     courses: getCourseList.data.map(course => ({
      name: course.courseName,
      id: course.courseId
    })),
    courseNames: getCourseList.data.map(course => course.courseName) 

    
   })

  }
});
